package com.hospital.wx.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hospital.wx.common.CommonResult;
import com.hospital.wx.controller.form.AddLikesForm;
import com.hospital.wx.controller.form.GetLikeIdForm;
import com.hospital.wx.pojo.Likes;
import com.hospital.wx.service.LikesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/patient/user/like")
@Tag(name = "LikesController", description = "点赞接口管理")
@Slf4j
public class LikesController {
    @Autowired
    private LikesService likesService;

    @PostMapping("/add")
    @Operation(summary = "添加点赞")
    @CrossOrigin(origins = "localhost:5173", allowCredentials = "true")
    public CommonResult addLikes(@Valid @RequestBody AddLikesForm form) {
        try {
            Likes likes = new Likes();
            likes.setPatientUserId(form.getPatientUserId());
            likes.setTargetId(form.getTargetId());
            likes.setTargetType(form.getTargetType());
            int rows = likesService.addLikes(likes);
            if (rows == 1) {
                return CommonResult.ok().put("rows", rows);
            }
            return CommonResult.failed("添加失败");
        } catch (Exception e) {
            log.error("添加过程中出现异常", e);
            return CommonResult.failed("添加过程中出现异常");
        }
    }

    @PostMapping("/cancel")
    @Operation(summary = "取消点赞")
    @CrossOrigin(origins = "localhost:5173", allowCredentials = "true")
    public CommonResult cancelLikes(@RequestParam("id") Integer id) {
        try {
            int rows = likesService.cancelLikes(id);
            if (rows == 1) {
                return CommonResult.ok().put("rows", rows);
            }
            return CommonResult.failed("取消点赞失败");
        } catch (Exception e) {
            log.error("取消点赞过程中出现错误", e);
            return CommonResult.failed("取消点赞过程中出现错误");
        }
    }
    /*
    * 如果已经点赞，执行取消点赞
    *  取消点赞需要点赞记录ID
    *  如果没有点赞ID，先获取
    * */
    @PostMapping("/getLikeId")
    @Operation(summary = "获取点赞ID")
    public CommonResult getLikeId(@Valid @RequestBody GetLikeIdForm form) {
        try {
            Map<String, Object> param = BeanUtil.beanToMap(form);
            Integer id = likesService.selectId(param);
            if (id != null) {
                return CommonResult.ok().put(CommonResult.RETURN_RESULT, id);
            }
            return CommonResult.failed("查询点赞ID失败");
        } catch (Exception e) {
            log.error("查询点赞ID过程中出现异常", e);
            return CommonResult.failed("查询点赞ID过程中出现异常");
        }
    }
}
